package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.water.*
import com.two.screen.water.balance.net.api.NormalApi24
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.ARouterUtils
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.utils.RxUtils
import com.two.screen.water.balance.utils.ToastUtil
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.utils.eventbus.EventCode.Companion.SOCKET_RESULT_PAY
import com.two.screen.water.balance.widget.dialog.SelectedPayDialog
import com.two.screen.water.balance.widget.dialog.WaitingPayDialog
import com.two.screen.water.balance.widget.dialog.WaitingPayDialog24
import kotlinx.android.synthetic.main.activity_collect_money24.*
import kotlinx.android.synthetic.main.activity_collect_money24.mGoBackLayout
import java.util.concurrent.TimeUnit


@Route(path = ARouterUtils.CollectMoneyActivity24)
class CollectMoneyActivity24 : BaseActivity() {
    val TAG = CollectMoneyActivity24::class.java.simpleName.plus("=>")
    override fun getContentLayout(): Any = R.layout.activity_collect_money24

    /*列表适配器*/
    lateinit var mHadChooseAdapter: HadChooseAdapter

    @JvmField @Autowired var mDataJson: String? = null
    private var mLocalOrderBean: LocalOrderBean? = null
    private var mSelectedPayDialog: SelectedPayDialog? = null
    private var mWaitingPayDialog24: WaitingPayDialog24? = null
    private var mCurOrderId: String? = null
    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        mLocalOrderBean = try {
            CommUtils.gson.fromJson(mDataJson, LocalOrderBean::class.java)
        } catch (e: Exception) {
            null
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        mTotalSizeTv.text = (mLocalOrderBean?.productList?.size ?: 0).toString()
        mTotalWeightTv.text = mLocalOrderBean?.totalWeightNet
        mTotalPriceTv.text = mLocalOrderBean?.totalPrice
        mBuyerPayTv.text = "￥${mLocalOrderBean?.totalPrice}"
        mSellerGetTv.text = "￥${mLocalOrderBean?.totalPrice}"
        initOrderRcy()
    }

    private fun initOrderRcy() {
        (mHadChooseRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mHadChooseAdapter = HadChooseAdapter()
        mHadChooseRecyclerView.layoutManager = LinearLayoutManager(this)
        mHadChooseRecyclerView.adapter = mHadChooseAdapter
        mHadChooseAdapter.bindToRecyclerView(mHadChooseRecyclerView)
        mHadChooseAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty3)

        //读取缓存
        mHadChooseAdapter.setNewData(mLocalOrderBean?.productList)
    }


    @SuppressLint("CheckResult")
    override fun initListener() {
        RxView.clicks(mHangOrderTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (mLocalOrderBean == null) {
                    ToastUtil.showToast("订单为空!")
                    return@subscribe
                }
                NormalApi24.putProductHang(mLocalOrderBean)
                    .compose(RxUtils.aLifecycle(this@CollectMoneyActivity24))
                    .subscribe(object : DialogObserver<NormalResultBean>(this@CollectMoneyActivity24) {
                        override fun dataIsNull(t: BaseBean<out NormalResultBean>) {
                            onSuccessNext(t)
                        }

                        override fun onSuccessNext(t: BaseBean<out NormalResultBean>) {
                            EventBusUtil.sendEvent(Event(EventCode.HANG_SUCCESS))
                            finish()
                        }
                    })
            }
        RxView.clicks(mCollectMoneyTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (mLocalOrderBean == null) {
                    ToastUtil.showToast("订单为空!")
                    return@subscribe
                }
                if (mSelectedPayDialog == null) mSelectedPayDialog = SelectedPayDialog(this)
                mSelectedPayDialog?.show()
                mSelectedPayDialog?.setSelectedPayDialogListener(object : SelectedPayDialog.SelectedPayDialogListener {
                    override fun onSelected(item: PayTypeBean) {
                        when (item.type) {
                            PayTypeBean.PAY_TYPE_REMAIN, PayTypeBean.PAY_TYPE_OWE -> {
                                NormalApi24.putProductOrder(mLocalOrderBean, item.type)
                                    .compose(RxUtils.aLifecycle(this@CollectMoneyActivity24))
                                    .subscribe(object : DialogObserver<PayResultBean>(this@CollectMoneyActivity24) {
                                        override fun dataIsNull(t: BaseBean<out PayResultBean>) {
                                            onSuccessNext(t)
                                        }

                                        override fun onSuccessNext(t: BaseBean<out PayResultBean>) {
                                            mCurOrderId = t.data?.orderId
                                            EventBusUtil.sendEvent(Event(EventCode.PAY_SUCCESS_NORMAL))
                                            finish()
                                        }
                                    })
                            }
                            PayTypeBean.PAY_TYPE_JUHE -> {
                                NormalApi24.putProductOrder(mLocalOrderBean, item.type)
                                    .compose(RxUtils.aLifecycle(this@CollectMoneyActivity24))
                                    .subscribe(object : DialogObserver<PayResultBean>(this@CollectMoneyActivity24) {
                                        override fun dataIsNull(t: BaseBean<out PayResultBean>) {
                                            onSuccessNext(t)
                                        }

                                        override fun onSuccessNext(t: BaseBean<out PayResultBean>) {
                                            //弹出等待框
                                            mCurOrderId = t.data?.orderId
                                            if (mWaitingPayDialog24 == null) mWaitingPayDialog24 = WaitingPayDialog24(this@CollectMoneyActivity24)
                                            mWaitingPayDialog24?.show()
                                            mWaitingPayDialog24?.setShowData(PayTypeBean.PAY_TYPE_JUHE, mLocalOrderBean!!, t.data)
                                            mWaitingPayDialog24?.setWaitingPayDialog24Listener(object : WaitingPayDialog24.WaitingPayDialogListener24() {
                                                override fun dismiss() {
                                                    //取消支付，应该需要把订单改成取消支付状态。
                                                    EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                                    mWaitingPayDialog24?.dismiss()
                                                }
                                            })
//                                            EventBusUtil.sendEvent(Event(EventCode.PAY_SUCCESS_NORMAL))
//                                            finish()
                                        }
                                    })
                            }
                            PayTypeBean.PAY_TYPE_SCAN -> {
                                //弹出等待框
                                if (mWaitingPayDialog24 == null) mWaitingPayDialog24 = WaitingPayDialog24(this@CollectMoneyActivity24)
                                mWaitingPayDialog24?.show()
                                mWaitingPayDialog24?.setShowData(PayTypeBean.PAY_TYPE_SCAN, mLocalOrderBean!!, null)
                                mWaitingPayDialog24?.setWaitingPayDialog24Listener(object : WaitingPayDialog24.WaitingPayDialogListener24() {
                                    override fun dismiss() {
                                        //取消支付，应该需要把订单改成取消支付状态。
                                        EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                        mWaitingPayDialog24?.dismiss()
                                    }

                                    override fun getAuthCodeSuccess(code: String) {
                                        d("getAuthCodeSuccess->code:$code,线程：${Thread.currentThread().name}")
                                        NormalApi24.putProductOrder(mLocalOrderBean, item.type, code)
                                            .compose(RxUtils.aLifecycle(this@CollectMoneyActivity24))
                                            .subscribe(object : DialogObserver<PayResultBean>(this@CollectMoneyActivity24) {
                                                override fun dataIsNull(t: BaseBean<out PayResultBean>) {
                                                    onSuccessNext(t)
                                                }

                                                override fun onSuccessNext(t: BaseBean<out PayResultBean>) {
                                                    mCurOrderId = t.data?.orderId
                                                    //TODO:这里还需要轮询订单支付结果
//                                                    EventBusUtil.sendEvent(Event(EventCode.PAY_SUCCESS_NORMAL))
//                                                    finish()
                                                }
                                            })
                                    }
                                })

                            }
                            else -> {
                                ToastUtil.showToast("尚未开发，敬请期待!")
                            }
                        }
                    }
                })
            }
        RxView.clicks(mGoBackLayout)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe { finish() }
        RxView.clicks(mCancelTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe { finish() }
    }

    /*购物车列表 适配器*/
    inner class HadChooseAdapter : BaseQuickAdapter<ProductBean, BaseViewHolder>(R.layout.item_collect_money_order_list24, null) {
        @SuppressLint("CheckResult")
        override fun convert(helper: BaseViewHolder, item: ProductBean) {
            helper
                .setText(R.id.item_tv1, String.format("%02d", (helper.bindingAdapterPosition + 1)))
                .setText(R.id.item_tv2, item.productName)
                .setText(R.id.item_tv3, item.productSpecs.toString())
                .setText(R.id.item_tv4, item.status.toString())
                .setText(R.id.item_tv5, item.productUnitPrice)
                .setText(R.id.item_tv6, String.format("%.1f", item.netWeight))
                .setText(R.id.item_tv7, String.format("%.2f", item.subTotalPrice))
                .setText(R.id.item_tv8, String.format("%.1f", item.roughWeight))
                .setText(R.id.item_tv9, String.format("%.1f", item.peelWeight))
                .getView<View>(R.id.item_root_view).apply {
                    isSelected = helper.bindingAdapterPosition % 2 == 0
                }
        }
    }

    override fun isRegisterEventBus(): Boolean = true
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            SOCKET_RESULT_PAY -> {
                val socketResponseBean = event.data as SocketResponseBean
                d("orderId:${socketResponseBean.data?.orderId},mCurOrderId:${mCurOrderId}")
                if (socketResponseBean.data?.orderId == mCurOrderId) {
                    EventBusUtil.sendEvent(Event(EventCode.PAY_SUCCESS_NORMAL))
                    //TODO:这里可能还需要接入打印。
                    if (mWaitingPayDialog24?.isShowing == true) {
                        mWaitingPayDialog24?.setPaySuccess()
                        mWaitingPayDialog24?.setWaitingPayDialog24Listener(object : WaitingPayDialog24.WaitingPayDialogListener24() {
                            override fun autoClosePay() {
                                mWaitingPayDialog24?.dismiss()
                                finish()
                            }
                        })
                        return
                    }
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.device?.name?.contains("USB", true) != true) return false
        if (event.action == KeyEvent.ACTION_DOWN) {//处理触发两次
            when (keyCode) {
                33 -> { //d("帐户/E")
                    mGoBackLayout.performClick()
                    return true
                }
                75 -> {// d("确认/'")
                    mCollectMoneyTv.performClick()
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}